import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_lendrecord_odoo_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_lendrecord.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_lendrecord/udt_tb_lendrecord_dialog.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class UdtTbLendrecordList extends StatefulWidget {
  UdtTbLendrecordList({Key? key}) : super(key: key);

  @override
  _UdtTbLendrecordListState createState() => _UdtTbLendrecordListState();
}

class _UdtTbLendrecordListState extends State<UdtTbLendrecordList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  UdtTbLendrecord udtTbLendrecord = UdtTbLendrecord();
  List<UdtTbLendrecord> selectedList = [];
  //档案项目
  late List<SelectOptionVO> docmenttypeIdList = [];
  late List<SelectOptionVO> departmentList = [];
  //借阅人员名称
  late List<SelectOptionVO> lenduserIdList = [];
  //文档借出状态
  late List<SelectOptionVO> statusList = [];

  DateFormat format = DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    var department =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbLendrecord.departmentId = department[0].toString();
    udtTbLendrecord.departmentName = department[1].toString();
    _loadSelectVO();
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  _loadSelectVO() async {
    departmentList = await DynamicDataApi.getModelSelect(
        model: "hr.department", name: "complete_name");
    docmenttypeIdList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "dms.documenttype",
        name: "documenttypename",
        key: "department_id",
        val: int.parse(udtTbLendrecord.departmentId!));
    //借阅人员名称
    // lenduserIdList = await DynamicDataApi.getModelSelect(model: 'user', name: 'user_name');
    statusList = [
      SelectOptionVO(value: '', label: ""),
      SelectOptionVO(value: '0', label: "未归还"),
      SelectOptionVO(value: '1', label: "已归还")
    ];
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '借阅开始时间',
            value: udtTbLendrecord.lendstartdate,
            lastDate: isNotBlank(udtTbLendrecord.lendenddate)
                ? format.parse(udtTbLendrecord.lendenddate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbLendrecord.lendstartdate = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbLendrecord.lendstartdate = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '借阅结束时间',
            value: udtTbLendrecord.lendenddate,
            firstDate: isNotBlank(udtTbLendrecord.lendstartdate)
                ? format.parse(udtTbLendrecord.lendstartdate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              udtTbLendrecord.lendenddate = v;
              setState(() {});
            },
            onSaved: (v) {
              udtTbLendrecord.lendenddate = v;
            },
          ),
          CrySelect(
            width: 280,
            label: '部门',
            dataList: departmentList,
            value: udtTbLendrecord.departmentId,
            onSaved: (v) => {udtTbLendrecord.departmentId = v},
            onChange: (v) async {
              if (udtTbLendrecord.departmentId != v) {
                formKey.currentState!.save();
                udtTbLendrecord.departmentId = v;
                udtTbLendrecord.documenttypeId = null;
                try {
                  docmenttypeIdList = await DynamicDataApi.getModelSelect(
                      active: false,
                      model: "dms.documenttype",
                      name: "documenttypename",
                      key: "department_id",
                      val: int.parse(v));
                } catch (e) {
                  docmenttypeIdList = [];
                }
                setState(() {});
              }
            },
          ),
          CrySelect(
            width: 280,
            label: '档案项目',
            dataList: docmenttypeIdList,
            value: udtTbLendrecord.documenttypeId,
            onSaved: (v) => {udtTbLendrecord.documenttypeId = v},
          ),
          CryInput(
            width: 160,
            label: '档案盒编号',
            value: udtTbLendrecord.documentno,
            onSaved: (v) {
              udtTbLendrecord.documentno = v;
            },
          ),
          CryInput(
            width: 140,
            label: '借阅人',
            value: udtTbLendrecord.lenduserName,
            onSaved: (v) => {udtTbLendrecord.lenduserName = v},
          ),
          CrySelect(
            width: 140,
            label: '状态',
            dataList: statusList,
            value: udtTbLendrecord.status,
            onSaved: (v) => {udtTbLendrecord.status = v},
          ),

        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('档案盒编号')),
        DataColumn(label: Text('档案盒名称')),
        DataColumn(label: Text('所属部门')),
        DataColumn(label: Text('档案项目')),
        DataColumn(label: Text('备注')),
        DataColumn(label: Text('借阅部门')),
        DataColumn(label: Text('借阅人')),
        DataColumn(label: Text('借阅时间')),
        DataColumn(label: Text('归还部门')),
        DataColumn(label: Text('归还人员')),
        DataColumn(label: Text('归还时间')),
      ],
      getCells: (m) {
        UdtTbLendrecord udtTbLendrecord = UdtTbLendrecord.fromMap(m);
        var flag = udtTbLendrecord.remark!.contains("\n");
        var remark;
        if (flag) {
          remark = udtTbLendrecord.remark!.split("\n")[0] + "...";
        } else {
          remark = udtTbLendrecord.remark;
        }
        return [
          DataCell(Text(udtTbLendrecord.documentno ?? '--')),
          DataCell(Text(udtTbLendrecord.documentname ?? '--')),
          DataCell(Text(udtTbLendrecord.departmentName ?? '--')),
          DataCell(Text(udtTbLendrecord.documenttypeName ?? '--')),
          DataCell(Text(remark)),
          DataCell(Text(udtTbLendrecord.lenddeptName ?? '--')),
          DataCell(Text(udtTbLendrecord.lenduserName ?? '--')),
          DataCell(Text(udtTbLendrecord.lenddate ?? '--')),
          DataCell(Text(udtTbLendrecord.returndeptName ?? '--')),
          DataCell(Text(udtTbLendrecord.returnuserName ?? '--')),
          DataCell(Text(udtTbLendrecord.returndate ?? '--')),
        ];
      },
    );
    _getSelectList();
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              isDisplayDesktop(context) ? buttonBar : Container()
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    udtTbLendrecord = UdtTbLendrecord();
    var deparment =
        StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    udtTbLendrecord.departmentId = deparment[0].toString();
    udtTbLendrecord.departmentName = deparment[1].toString();
    formKey.currentState!.reset();
    // tableKey.currentState?.loadData(PageModel());
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    var filter = {};
    if (udtTbLendrecord.lenduserName != null &&
        udtTbLendrecord.lenduserName != "") {
      filter = {
        "filterX2": [
          'lenduser_id',
          ['name', 'like', '%${udtTbLendrecord.lenduserName}%']
        ]
      };
    }
    ResponseBodyApi responseBodyApi = await UdtTbLendrecordOdooApi.page(data: {
      "page": page,
      "domainList": udtTbLendrecord.toDomainList(),
      "filter": filter
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: UdtTbLendrecordDialog(),
      ),
    ).then((v) {
      if (v != null) {
        udtTbLendrecord = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<UdtTbLendrecord>((e) => UdtTbLendrecord.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.add) {
          // _edit(null);
        } else if (v == OperationType.edit) {
          // _edit(selectedList[0]);
        } else if (v == OperationType.delete) {
          // cryConfirm(context, S.of(context).confirmDelete,
          //         (context) async {
          //       _delete(selectedList);
          //     });
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
      ],
    );
  }
}
